package net.sh.dpinfrastructure.mail;

import java.io.File;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import net.sh.dpinfrastructure.config.DPConfig;
import net.sh.dpinfrastructure.exception.DPException;
import net.sh.dpinfrastructure.exception.DPException.Level;
import net.sh.dpinfrastructure.exception.DPException.Modal;
import net.sh.dpinfrastructure.exception.DPException.Type;
import net.sh.dpinfrastructure.log.DPLogger;


/**
 * 
 * DPMail的javax.mail实现
 * 
 * 
 * @version 1.0
 * @since JDK1.7
 * @author shaohui
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2015 SunTime Co'Ltd Inc. All rights reserved.
 * @date 2015年9月2日 下午3:48:41
 */
public class DPJavaMail implements DPMail {
    
    private static final DPLogger LOGGER = new DPLogger(DPMail.class);
    
    private Session session;
    
    /**
     * 发件人
     */
    private Address from;
    
    public DPJavaMail(DPConfig config) {
        Properties props = new Properties();
        // 邮箱服务器地址
        String host = config.get("mail.host");
        // 用户名
        final String username = config.get("mail.username");
        // 密码
        final String password = config.get("mail.password");
        
        if (StringUtils.isBlank(host) || StringUtils.isBlank(username) || StringUtils.isBlank("password")) {
            throw new DPException("配置缺失");
        }
        props.put("mail.smtp.host", host);
        //是否开启验证
        props.put("mail.smtp.auth", config.getBoolValue("mail.auth", false));
        //邮箱协议
        props.put("mail.transport.protocol", config.get("mail.protocol", "smtp"));  
        
        this.session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        
        String nickname = config.get("mail.nickname");
        try {
            if (StringUtils.isBlank(nickname)) {
                from = new InternetAddress(config.get("mail.sender"));
            } else {
                from = new InternetAddress(config.get("mail.sender"), MimeUtility.encodeText(nickname));
            }
        } catch (Exception e) {
            throw new DPException("设置收件人失败", e);
        }
        LOGGER.debug("mail对话创建成功");
    }
    
    @Override
    public void sendSimpleMail(Set<String> recipients, String title, String msg) {
        // 创建邮件对象  
        Message message = new MimeMessage(session);
        try {
            // 发件人 
            message.setFrom(from);  
            // 多个收件人
            message.setRecipients(RecipientType.TO, InternetAddress.parse(StringUtils.join(recipients, ",")));  
            // 主题
            message.setSubject(title);
            message.setContent(msg, "text/plain;charset=utf-8");  
            // 连接邮件服务器、发送邮件、关闭连接，全干了  
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
            throw new DPException(Level.ERROR, Modal.DATAPLATFORM, Type.NETWORK, "邮件发送失败", e);
        }
        
    }

    @Override
    public void sendComplexMail(Set<String> recipients, String title, String msg, List<File> attachments) {
        // 创建邮件对象  
        Message message = new MimeMessage(session);
        try {
            // 发件人 
            message.setFrom(from);  
            // 多个收件人
            message.setRecipients(RecipientType.TO, InternetAddress.parse(StringUtils.join(recipients, ",")));  
            // 主题
            message.setSubject(title);
            
            // 消息体
            MimeMultipart messageBody = new MimeMultipart();
            
            // 文字部分，可以是html模板
            MimeBodyPart text = new MimeBodyPart();
            text.setContent(msg, "text/html;charset=UTF-8");
            messageBody.addBodyPart(text);
            
            // 附件
            if (CollectionUtils.isNotEmpty(attachments)) {
                // 添加附件
                for (File attachment : attachments) {
                    MimeBodyPart attachmentPart = new MimeBodyPart();
                    DataHandler dh = new DataHandler(new FileDataSource(attachment));
                    attachmentPart.setDataHandler(dh);
                    attachmentPart.setFileName(dh.getName());  //
                    messageBody.addBodyPart(attachmentPart);
                }
            }
            message.setContent(messageBody, "text/html;charset=utf-8");  
            // 发送邮件
            Transport.send(message);  
        } catch (Exception e) {
            e.printStackTrace();
            throw new DPException(Level.ERROR, Modal.DATAPLATFORM, Type.NETWORK, "邮件发送失败", e);
        }
    }
    
}
